import java.util.ArrayDeque;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    int maxDepth = 0;
    int bottomLeftValue;

    public int findBottomLeftValue(TreeNode root) {
        findBottomLeftValue(root, 1);
        return bottomLeftValue;
    }

    void findBottomLeftValue(TreeNode root, int curDepth) {
        if (root.left == null && root.right == null) {
            if (curDepth > maxDepth) {
                maxDepth = curDepth;
                bottomLeftValue = root.val;
            }
            return;
        }
        if (root.left != null) {
            findBottomLeftValue(root.left, curDepth + 1);
        }
        if (root.right != null) {
            findBottomLeftValue(root.right, curDepth + 1);
        }
    }
}

//层序遍历
class Solution1 {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ans = queue.peek().val;
            while (size-- > 0) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }
        return ans;
    }
}
